package com.example.controller;

import com.example.model.PointsRecord;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/points")
@Tag(name = "积分管理", description = "用户积分的获取、消费和管理")
public class PointsController {

    // ==================== 用户端积分接口 ====================
    @GetMapping("/user/balance")
    @Operation(summary = "获取用户积分余额")
    public ResponseEntity<Map<String, Object>> getUserPointsBalance() {
        // 这里应该从SecurityContext获取当前用户
        Map<String, Object> balance = new HashMap<>();
        balance.put("totalPoints", 1250);
        balance.put("availablePoints", 1200);
        balance.put("frozenPoints", 50);
        balance.put("expiringSoon", 100); // 即将过期的积分
        balance.put("expiryDate", LocalDateTime.now().plusDays(30));
        return ResponseEntity.ok(balance);
    }

    @GetMapping("/user/records")
    @Operation(summary = "获取用户积分记录")
    public ResponseEntity<Page<Map<String, Object>>> getUserPointsRecords(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) String operation) {
        
        Pageable pageable = PageRequest.of(page, size, Sort.by("createdAt").descending());
        
        // 模拟积分记录数据
        List<Map<String, Object>> records = List.of(
            Map.of(
                "id", 1L,
                "type", "EARN",
                "operation", "ORDER_COMPLETE",
                "points", 50,
                "balanceBefore", 1200,
                "balanceAfter", 1250,
                "description", "订单完成奖励",
                "createdAt", LocalDateTime.now().minusDays(1)
            ),
            Map.of(
                "id", 2L,
                "type", "SPEND",
                "operation", "REDEEM_COUPON",
                "points", -100,
                "balanceBefore", 1300,
                "balanceAfter", 1200,
                "description", "兑换优惠券",
                "createdAt", LocalDateTime.now().minusDays(3)
            )
        );
        
        Page<Map<String, Object>> recordPage = Page.empty(pageable);
        return ResponseEntity.ok(recordPage);
    }

    @GetMapping("/user/summary")
    @Operation(summary = "获取用户积分汇总")
    public ResponseEntity<Map<String, Object>> getUserPointsSummary() {
        Map<String, Object> summary = new HashMap<>();
        summary.put("totalEarned", 2500);
        summary.put("totalSpent", 1250);
        summary.put("currentBalance", 1250);
        summary.put("thisMonthEarned", 150);
        summary.put("thisMonthSpent", 50);
        summary.put("membershipLevel", "GOLD");
        summary.put("nextLevelPoints", 750); // 升级到下一等级还需要的积分
        return ResponseEntity.ok(summary);
    }

    // ==================== 积分兑换接口 ====================
    @GetMapping("/rewards")
    @Operation(summary = "获取积分兑换商品列表")
    public ResponseEntity<List<Map<String, Object>>> getPointsRewards() {
        List<Map<String, Object>> rewards = List.of(
            Map.of(
                "id", 1L,
                "name", "10元优惠券",
                "description", "满50元可用",
                "pointsCost", 100,
                "stock", 500,
                "category", "COUPON",
                "imageUrl", "/images/coupon-10.png",
                "isAvailable", true
            ),
            Map.of(
                "id", 2L,
                "name", "20元优惠券",
                "description", "满100元可用",
                "pointsCost", 200,
                "stock", 300,
                "category", "COUPON",
                "imageUrl", "/images/coupon-20.png",
                "isAvailable", true
            ),
            Map.of(
                "id", 3L,
                "name", "精美洗衣袋",
                "description", "高品质洗衣袋一个",
                "pointsCost", 500,
                "stock", 50,
                "category", "GIFT",
                "imageUrl", "/images/laundry-bag.png",
                "isAvailable", true
            )
        );
        return ResponseEntity.ok(rewards);
    }

    @PostMapping("/redeem")
    @Operation(summary = "兑换积分商品")
    public ResponseEntity<Map<String, Object>> redeemPoints(
            @RequestBody Map<String, Object> redeemData) {
        
        Long rewardId = ((Number) redeemData.get("rewardId")).longValue();
        Integer quantity = (Integer) redeemData.getOrDefault("quantity", 1);
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "兑换成功");
        response.put("redeemId", 1L);
        response.put("pointsUsed", 100);
        response.put("remainingPoints", 1150);
        return ResponseEntity.ok(response);
    }

    @GetMapping("/redeem/history")
    @Operation(summary = "获取兑换历史")
    public ResponseEntity<Page<Map<String, Object>>> getRedeemHistory(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        Pageable pageable = PageRequest.of(page, size, Sort.by("createdAt").descending());
        Page<Map<String, Object>> emptyPage = Page.empty(pageable);
        return ResponseEntity.ok(emptyPage);
    }

    // ==================== 管理端积分接口 ====================
    @GetMapping("/admin/records")
    @Operation(summary = "获取积分记录列表")
    public ResponseEntity<Page<Map<String, Object>>> getPointsRecords(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) String operation) {
        
        Pageable pageable = PageRequest.of(page, size, Sort.by("createdAt").descending());
        Page<Map<String, Object>> emptyPage = Page.empty(pageable);
        return ResponseEntity.ok(emptyPage);
    }

    @PostMapping("/admin/adjust")
    @Operation(summary = "手动调整用户积分")
    public ResponseEntity<Map<String, Object>> adjustUserPoints(
            @RequestBody Map<String, Object> adjustData) {
        
        Long userId = ((Number) adjustData.get("userId")).longValue();
        Integer points = (Integer) adjustData.get("points");
        String reason = (String) adjustData.get("reason");
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "积分调整成功");
        response.put("recordId", 1L);
        return ResponseEntity.ok(response);
    }

    @GetMapping("/admin/statistics")
    @Operation(summary = "获取积分统计")
    public ResponseEntity<Map<String, Object>> getPointsStatistics() {
        Map<String, Object> statistics = new HashMap<>();
        
        statistics.put("totalUsers", 1250L);
        statistics.put("activeUsers", 980L);
        statistics.put("totalPointsIssued", 125000L);
        statistics.put("totalPointsRedeemed", 45000L);
        statistics.put("totalPointsExpired", 5000L);
        
        statistics.put("todayPointsIssued", 1500L);
        statistics.put("todayPointsRedeemed", 800L);
        statistics.put("todayActiveUsers", 150L);
        
        statistics.put("averagePointsPerUser", 640.0);
        statistics.put("redemptionRate", 36.0);
        
        // 积分分布统计
        statistics.put("pointsDistribution", List.of(
            Map.of("range", "0-100", "count", 200),
            Map.of("range", "101-500", "count", 450),
            Map.of("range", "501-1000", "count", 350),
            Map.of("range", "1001-2000", "count", 180),
            Map.of("range", "2000+", "count", 70)
        ));
        
        return ResponseEntity.ok(statistics);
    }

    // ==================== 积分规则管理 ====================
    @GetMapping("/rules")
    @Operation(summary = "获取积分规则")
    public ResponseEntity<Map<String, Object>> getPointsRules() {
        Map<String, Object> rules = new HashMap<>();
        
        rules.put("earnRules", Map.of(
            "orderComplete", Map.of("rate", 0.05, "description", "订单完成按金额5%获得积分"),
            "signUp", Map.of("points", 100, "description", "注册奖励100积分"),
            "dailySign", Map.of("points", 10, "description", "每日签到奖励10积分"),
            "birthday", Map.of("points", 200, "description", "生日奖励200积分"),
            "referral", Map.of("points", 50, "description", "推荐好友奖励50积分")
        ));
        
        rules.put("redeemRules", Map.of(
            "minPoints", 50,
            "maxPointsPerOrder", 1000,
            "pointsToMoney", 0.01, // 1积分=0.01元
            "expiryDays", 365
        ));
        
        return ResponseEntity.ok(rules);
    }

    @PutMapping("/rules")
    @Operation(summary = "更新积分规则")
    public ResponseEntity<Map<String, Object>> updatePointsRules(
            @RequestBody Map<String, Object> rules) {
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "积分规则更新成功");
        return ResponseEntity.ok(response);
    }

    // ==================== 积分任务管理 ====================
    @GetMapping("/tasks")
    @Operation(summary = "获取积分任务列表")
    public ResponseEntity<List<Map<String, Object>>> getPointsTasks() {
        List<Map<String, Object>> tasks = List.of(
            Map.of(
                "id", 1L,
                "name", "每日签到",
                "description", "每日签到可获得10积分",
                "points", 10,
                "type", "DAILY",
                "isCompleted", false,
                "progress", 0,
                "target", 1
            ),
            Map.of(
                "id", 2L,
                "name", "完成首单",
                "description", "完成第一个订单可获得100积分",
                "points", 100,
                "type", "ONCE",
                "isCompleted", true,
                "progress", 1,
                "target", 1
            )
        );
        return ResponseEntity.ok(tasks);
    }

    @PostMapping("/tasks/{id}/complete")
    @Operation(summary = "完成积分任务")
    public ResponseEntity<Map<String, Object>> completePointsTask(@PathVariable Long id) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "任务完成，积分已发放");
        response.put("pointsEarned", 10);
        return ResponseEntity.ok(response);
    }
}
